package com.woniuxy.automotivemanagementsystem.controller;

import com.woniuxy.automotivemanagementsystem.entity.News;
import com.woniuxy.automotivemanagementsystem.entity.vo.NewsVo;
import com.woniuxy.automotivemanagementsystem.service.NewsService;
import com.woniuxy.automotivemanagementsystem.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static cn.hutool.core.date.DateTime.now;

@RestController
@RequestMapping("/news")
@CrossOrigin
public class NewsController {
    @Autowired
    private NewsService newsService;
    /*
    * 所有新闻菜单中的条件查询所有方法
    * */
    @PostMapping("/queryCondition")
    public Result queryCondition(@RequestBody NewsVo newsFrom){
        return newsService.queryCondition(newsFrom);
    }
    /*
    * 删除单个新闻方法
    * */
    @PutMapping("/delete")
    public Result delete(@RequestBody News news) {
        if (news == null || news.getNid() == null) {
            return Result.error("参数不能为空");
        }
        newsService.lambdaUpdate()
                .eq(News::getNid, news.getNid())
                .set(News::getStatus, news.getStatus() == 1 ? 0 : 1)
                .update();
        return Result.success(true);
    }
    /*
    * 批量删除新闻方法
    * */
    @PutMapping("/updateByNews")
    public Result updateByNews(@RequestBody List<News> news) {
        if (news == null || news.isEmpty()) {
            return Result.error("参数不能为空");
        }
        for (News n : news) {
            newsService.lambdaUpdate()
                    .eq(News::getNid, n.getNid())
                    .set(News::getStatus, 1)
                    .update();
        }
        return Result.success(true);
    }
    /*
    * 新增新闻接口
    * */
    @PostMapping("/add")
    public Result add(@RequestBody News news){
        if (news == null) {
            return Result.error("参数不能为空");
        }
        news.setStatus(0);
        news.setCreatetime(now());
        newsService.save(news);
        return Result.success(true);
    }
    /*
    * 修改新闻接口
    * */
    @PutMapping("/update")
    public Result update(@RequestBody News news){
        if (news == null || news.getNid() == null) {
            return Result.error("参数不能为空");
        }
        newsService.lambdaUpdate()
                .eq(News::getNid, news.getNid())
                .set(News::getType, news.getType())
                .set(News::getTitle, news.getTitle())
                .set(News::getContent, news.getContent())
                .set(News::getRemarks, news.getRemarks())
                .set(News::getAuthor, news.getAuthor())
                .update();
        return Result.success(true);
    }
}
